﻿using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Text;

namespace Wabo.Util
{
    public class ActiveDirectoryHelper
    {
        private static string _domainName;
        /// <summary>
        /// Sets the domain name to be used by others functions
        /// </summary>
        /// <param name="domainName"></param>
        public static void SetDomain(string domainName)
        {
            _domainName = domainName;
        }
        /// <summary>
        /// Returns all users in Domain Users group
        /// </summary>
        /// <returns></returns>
        public List<Principal> GetDomainUsers()
        {
            return GetDomainGroupUsers("Domain Users");
        }
        /// <summary>
        /// Returns  list of users in an active directoy group
        /// </summary>
        /// <param name="groupName"></param>        
        /// <returns></returns>
        public static List<Principal> GetDomainGroupUsers(string groupName)
        {
            var usersOfGroup = new List<Principal>();
            var principalContext = new PrincipalContext(ContextType.Domain, _domainName);
            var grp = GroupPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, groupName);
            if (grp != null)
            {
                usersOfGroup.AddRange(grp.GetMembers(false));
                grp.Dispose();
                principalContext.Dispose();
                return usersOfGroup;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        ///  check for user account in active directory domain
        /// </summary>
        /// <param name="usr">Username</param>
        /// <param name="pwd">Password</param>        
        /// <returns></returns>
        public static bool IsAuthenticated(string usr, string pwd)
        {

            using (var pc = new PrincipalContext(ContextType.Domain, _domainName))
            {
                var up = UserPrincipal.FindByIdentity(pc, usr);
                bool isValid = pc.ValidateCredentials(usr, pwd);
                return isValid;
            }
        }
    }
}
